import { LoadingController, AlertController, ToastController, App } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import { PublicCompoentsProvider } from "../providers/public-compoents/public-compoents";
import 'rxjs/add/operator/toPromise';



@Injectable()
export class AppService {
    public domain = "http://second.noyechina.cn/index.php/shop";
    // public domain = "http://two.bjyblkj.cn/index.php/shop";

    public userId;

    constructor(public storage: Storage,
        public http: Http,
        public loadingCtrl: LoadingController,
        private alertCtrl: AlertController,
        private toastCtrl: ToastController,
        public PublicProvider: PublicCompoentsProvider,
        public app: App) {
        this.storage.get('userInfo').then(val => {
            val ? this.userId = val.id : ''
        })
    }

    alert(message, callback?) {
        let alert = this.alertCtrl.create({
            title: '提示',
            message: message,
            buttons: [{
                text: "确定",
                handler: () => {
                    if (callback) {
                        callback();
                    }
                }
            }]
        });
        alert.present();
    }
    showPrompt(message, placeholder, callback) {
        const prompt = this.alertCtrl.create({
            message: message,
            inputs: [
                {
                    name: 'input',
                    type: 'tel',
                    placeholder: placeholder
                },
            ],
            buttons: [
                {
                    text: '确定',
                    handler: data => {
                        callback(data);
                    }
                }
            ]
        });
        prompt.present();
    }
    showPrompt2(message, callback) {
        const prompt = this.alertCtrl.create({
            title: '确认购买',
            message: message,
            enableBackdropDismiss: false,
            buttons: [
                {
                    text: '取消',
                    handler: data => {
                        callback(false);
                    }
                },
                {
                    text: '确定',
                    handler: data => {
                        callback(true);
                    }
                }
            ]
        });
        prompt.present();
    }

    toast(message, callback?) {
        let toast = this.toastCtrl.create({
            message: message,
            duration: 2000,
            position: 'middle',
            dismissOnPageChange: true
        });
        toast.present();
        if (callback) {
            callback();
        }
    }
    //时间戳格式化
    getNowFormatDate(date, hashour) {
        var now = new Date(date);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date: any = now.getDate();
        var hour: any = now.getHours();
        if (hour < 10) { hour = "0" + hour }
        var minute: any = now.getMinutes();
        if (minute < 10) { minute = "0" + minute }
        var second: any = now.getSeconds();
        if (second < 10) { second = "0" + second }
        console.log(year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second)
        if (hashour) {
            return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
        } else {
            return year + "-" + month + "-" + date;
        }
    }
    setItem(key: string, obj: any) {
        try {
            var json = JSON.stringify(obj);
            window.localStorage[key] = json;
        }
        catch (e) {
            console.error("window.localStorage error:" + e);
        }
    }
    getItem(key: string, callback) {
        try {
            var json = window.localStorage[key];
            var obj = JSON.parse(json);
            callback(obj);
        }
        catch (e) {
            console.error("window.localStorage error:" + e);
        }
    }


    public post(url: string, params, callback, isShowLoading: boolean = true) {
        isShowLoading ? this.PublicProvider.showLoading() : '';
        params.count = 20;
        console.log(url, params)
        url = this.domain + url
        let options = new RequestOptions({
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        });
        let datas = this.toQueryString(params);
        this.http.post(url, datas, options).toPromise().then(res => {
            if (res.json().code == 1) {
                callback(res.json())
            } else {
                console.log('操作不成功', res.json().msg)
                callback(res.json())
            }
            isShowLoading ? this.PublicProvider.hideLoading() : '';
        }).catch(error => {
            console.log(error)
            callback(error)
        })

    };

    private toQueryString(obj) {
        let result = [];
        for (let key in obj) {
            key = encodeURIComponent(key);
            let values = obj[key];
            if (values && values.constructor == Array) {
                let queryValues = [];
                for (let i = 0, len = values.length, value; i < len; i++) {
                    value = values[i];
                    queryValues.push(this.toQueryPair(key, value));
                }
                result = result.concat(queryValues);
            } else {
                result.push(this.toQueryPair(key, values));
            }
        }
        return result.join('&');
    };

    private toQueryPair(key, value) {
        if (typeof value == 'undefined') {
            return key;
        }
        return key + '=' + encodeURIComponent(value === null ? '' : String(value));
    };
    //获取手机验证码
    public askTel(tel, callback) {
        this.post('/user/sendMsg', { phone: tel }, res => {
            callback(res)
        }, false)
    }
    //验证手机验证码
    public verifyAskTel(userId, tel, code, callback) {
        this.post('/user/bindingPhone', { user_id: userId, phone: tel, code: code }, res => {
            callback(res)
        })
    }

    // 通过id获取用户信息 或者刷新本地储存信息
    public getUserInfo(userId, callback?) {
        this.post('/apiindex/index_userinfo', { userinfo: 'userinfo', userid: userId }, res => {
            console.log('用户信息', res)
            if (res.code == 1) {
                this.storage.set('userInfo', res.data)

                callback(res)
            }
        }, false)
    }
    // 用户余额
    public getUserMoney(callback) {
        this.post('/apiindex/index_userinfo', { userinfo: 'userinfo', userid: this.userId }, res => {
            if (res.code == 1) {
                this.storage.set('userInfo', res.data)
                this.storage.set('userId', res.data.id)
                callback(res.data.money)
            }
        }, false)
    }

    //绑定手机号
    public bindPhone() {
        this.storage.get('userInfo').then(val => {
            if (val) {
                let userId = val.id;
                this.showPrompt('请先绑定手机号', '请输入正确的11位手机号', res => {
                    if (res.input.length == 11) {
                        let tel = res.input;
                        this.askTel(res.input, res0 => {
                            console.log('绑定号码：', res0)
                            if (res0.code == 1) {
                                this.showPrompt('验证码发送成功', '请输入验证码', res1 => {
                                    if (res1.input.length == 6) {
                                        this.verifyAskTel(userId, tel, res1.input, res2 => {
                                            console.log(res2)
                                            if (res2.code == 1) {
                                                this.alert('操作成功')
                                                this.getUserInfo(userId)
                                            } else {
                                                this.alert(res2.msg)
                                            }
                                        })
                                    } else {
                                        this.alert('操作失败，验证码不正确')
                                    }
                                })
                            } else {
                                this.alert(res0.msg)
                            }
                        })
                    } else {
                        this.alert('操作失败，手机号不正确')
                    }
                })
            }

        })

    }
    // 检测是否绑定手机号
    hasBindTel(doBindFun: boolean, callback?) {
        console.log('开始检测是否绑定手机号')
        this.storage.get('userInfo').then(val => {
            if (val) {
                if (val.phone == 0) {
                    this.getUserInfo(this.userId, res => {
                        if (res.code == 1 && res.data.phone !== 0) {
                            console.log('用户绑定了手机号', res.data.phone);
                            callback ? callback(true) : '';
                            this.storage.set('userInfo', res.data)
                            this.storage.set('userId', res.data.id)
                            return;
                        } else {
                            console.log('用户未绑定手机号');
                            callback ? callback(false) : '';
                            if (doBindFun) {
                                this.bindPhone();
                            }
                        }
                    })

                } else {
                    console.log('用户绑定了手机号', val.phone);
                    callback ? callback(true) : '';

                }
            }
        })
    }


}
